<template>
    <div class="gantt-chart-container">
      <div class="gantt-header">
        <div class="gantt-row-header"></div>
        <div class="gantt-time-scale">
          <!-- 年份显示区域 -->
          <div class="year-header-row">
            <template v-for="(yearInfo, index) in yearsInView" :key="'year-header-' + index">
              <div class="year-header" :style="{ width: yearInfo.days * dayWidth + 'px' }">{{ yearInfo.name }}</div>
            </template>
          </div>
          <!-- 月份显示区域 -->
          <div class="month-header-row">
            <template v-for="(monthInfo, index) in monthsInView" :key="'month-header-' + index">
              <div class="month-header" :style="{ width: monthInfo.days * dayWidth + 'px' }">{{ monthInfo.name }}</div>
            </template>
          </div>
          <!-- 日期和星期显示区域（合并到同一行） -->
          <div class="date-scale">
            <div 
              class="date-cell" 
              v-for="(date, index) in allDatesInView" 
              :key="'date-' + index"
            >
              <div class="day-cell">{{ date.getDate() }}</div>
              <div class="weekday-cell">{{ getWeekday(date.getFullYear(), date.getMonth() + 1, date.getDate()) }}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="gantt-body">
        <div class="gantt-rows">
          <div class="gantt-row" v-for="(item, index) in chartData" :key="index">
            <div class="gantt-row-info">
              <div class="row-label">产线: {{ item.productLine }}</div>
              <div class="row-order">订单编号: {{ item.orderNumber }}</div>
              <div class="row-plan">计划: {{ item.plannedQuantity }} 完工: {{ item.completedQuantity }} 次品: {{ item.defectiveQuantity }}</div>
            </div>
            <div class="gantt-bars">
              <div class="gantt-grid-overlay"></div>
              <div
                class="gantt-bar"
                :style="getBarStyle(item)"
              >
                <div class="completion-tooltip">
                  完工进度: {{ getCompletionProgress(item) }}%
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="jsx">
  import { ref, reactive, getCurrentInstance, onMounted, computed } from "vue";
  
  const { proxy } = getCurrentInstance();
  const chartData = ref([]);
  
  // 模拟月份和日期数据
  const daysInAugust = computed(() => Array.from({ length: 31 }, (_, i) => i + 1));
  const daysInSeptember = computed(() => Array.from({ length: 19 }, (_, i) => i + 1));
  
  const getWeekday = (year, month, day) => {
    const date = new Date(year, month - 1, day);
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    return weekdays[date.getDay()];
  };
  
  const getCompletionProgress = (item) => {
    const planned = parseFloat(item.plannedQuantity);
    const completed = parseFloat(item.completedQuantity);
    if (planned > 0) {
      const progress = (completed / planned) * 100;
      return progress.toFixed(1); // 保留一位小数
    }
    return 0;
  };
  
  const dayWidth = ref(25); // 调整每天的宽度以匹配图片效果
  const startDateForScale = ref(new Date()); // 初始设置为当前日期，后续动态更新
  const endDateForScale = ref(new Date()); // 初始设置为当前日期，后续动态更新
  
  const allDatesInView = computed(() => {
    const dates = [];
    let currentDate = new Date(startDateForScale.value);
    while (currentDate <= endDateForScale.value) {
      dates.push(new Date(currentDate));
      currentDate.setDate(currentDate.getDate() + 1);
    }
    return dates;
  });
  
  const monthsInView = computed(() => {
    const months = [];
    let currentMonth = -1;
    let monthIndex = -1;
  
    allDatesInView.value.forEach(date => {
      if (date.getMonth() !== currentMonth) {
        currentMonth = date.getMonth();
        monthIndex++;
        months.push({
          name: `${date.getMonth() + 1}月`,
          days: 0,
          year: date.getFullYear(), // 添加年份信息
        });
      }
      months[monthIndex].days++;
    });
    return months;
  });
  
  const yearsInView = computed(() => {
    const years = [];
    let currentYear = -1;
    let yearIndex = -1;
  
    allDatesInView.value.forEach(date => {
      if (date.getFullYear() !== currentYear) {
        currentYear = date.getFullYear();
        yearIndex++;
        years.push({
          name: `${date.getFullYear()}年`,
          days: 0,
        });
      }
      years[yearIndex].days++;
    });
    return years;
  });
  
  const getMonthName = (monthIndex) => {
    const monthNames = ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"];
    return monthNames[monthIndex];
  };
  
  const totalDays = computed(() => {
    const diffTime = Math.abs(endDateForScale.value - startDateForScale.value);
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
  });
  
  const getBarStyle = (item) => {
    const start = new Date(item.startDate);
    const end = new Date(item.endDate);
    const diffStart = Math.abs(start - startDateForScale.value);
    const daysFromStart = Math.floor(diffStart / (1000 * 60 * 60 * 24));
  
    const diffDuration = Math.abs(end - start);
    const durationDays = Math.ceil(diffDuration / (1000 * 60 * 60 * 24)) + 1;
    const totalPlannedWidth = durationDays * dayWidth.value; // 计算总计划宽度
  
    const planned = parseFloat(item.plannedQuantity);
    const completed = parseFloat(item.completedQuantity);
    let completionRatio = 0;
    if (planned > 0) {
      completionRatio = completed / planned; // 计算完成率 (0-1)
    }
  
    const left = daysFromStart * dayWidth.value;
    const width = totalPlannedWidth * completionRatio; // 宽度由完成率决定
  
    return {
      left: `${left}px`,
      width: `${width}px`,
      backgroundColor: '#42b983',
      position: 'absolute',
      height: '20px',
      borderRadius: '3px',
    };
  };
  
  const fetchChartData = async () => {
    try {
      const response = await proxy.http.get('/api/Maintenance/GetAllTicketsLedger');
      // 假设response.data是包含甘特图所需数据的数组
      // 这里的key需要根据实际API返回的数据结构进行调整
      chartData.value = response.data.map(item => ({
        productLine: item.bomCode,
        orderNumber: item.documentcode,
        plannedQuantity: item.plannedquantity,
        completedQuantity: item.alreadyproduced,
        defectiveQuantity: item.unqualifiedquantity,
        startDate: item.plannedtarttime,
        endDate: item.createTime, // 结束日期现在映射到 createTime 字段
      }));
  
      // 根据动态数据调整时间刻度范围
      if (chartData.value.length > 0) {
        let minDate = new Date(chartData.value[0].startDate);
        let maxDate = new Date(chartData.value[0].endDate);
  
        chartData.value.forEach(item => {
          const start = new Date(item.startDate);
          const end = new Date(item.endDate);
          if (start < minDate) minDate = start;
          if (end > maxDate) maxDate = end;
        });
  
        // 将最小开始日期设置为月份的第一天
        startDateForScale.value = new Date(minDate.getFullYear(), minDate.getMonth(), 1);
        // 将最大结束日期设置为月份的最后一天
        endDateForScale.value = new Date(maxDate.getFullYear(), maxDate.getMonth() + 1, 0);
  
      } else {
        // 如果没有数据，设置一个默认的时间范围，例如当前月份
        const now = new Date();
        startDateForScale.value = new Date(now.getFullYear(), now.getMonth(), 1);
        endDateForScale.value = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      }
  
      // 模拟数据 (如果API暂时无法调用，可以使用此数据进行测试)
      // chartData.value = [
      //   {
      //     productLine: '瑞阳传感器',
      //     orderNumber: 'DD2024072201',
      //     plannedQuantity: 3000,
      //     completedQuantity: 600,
      //     defectiveQuantity: 5,
      //     startDate: '2024-07-22',
      //     endDate: '2024-08-05',
      //   },
      //   {
      //     productLine: '7841852963',
      //     orderNumber: '741852963',
      //     plannedQuantity: 6521,
      //     completedQuantity: 111,
      //     defectiveQuantity: 752,
      //     startDate: '2024-08-06',
      //     endDate: '2024-08-20',
      //   },
      //   {
      //     productLine: '18975325846',
      //     orderNumber: '7894563321',
      //     plannedQuantity: 7522,
      //     completedQuantity: 450,
      //     defectiveQuantity: 2,
      //     startDate: '2024-08-21',
      //     endDate: '2024-09-04',
      //   },
      //   {
      //     productLine: '2242222',
      //     orderNumber: '186441222',
      //     plannedQuantity: 450,
      //     completedQuantity: 420,
      //     defectiveQuantity: 12,
      //     startDate: '2024-09-05',
      //     endDate: '2024-09-19',
      //   },
      // ];
  
    } catch (error) {
      console.error('Error fetching chart data:', error);
    }
  };
  
  onMounted(() => {
    fetchChartData();
  });
  </script>
  
  <style lang="less" scoped>
  .gantt-chart-container {
    display: flex;
    flex-direction: column;
    border: 1px solid #000000; /* 调整边框颜色为纯黑色 */
    font-family: Arial, sans-serif;
    overflow-x: auto;
  }
  
  .gantt-header {
    display: flex;
    border-bottom: 1px solid #000000; /* 调整边框颜色为纯黑色 */
    background-color: #f5f5f5;
  }
  
  .gantt-row-header {
    min-width: 300px; /* 调整以适应左侧信息，增加宽度 */
    border-right: 1px solid #000000; /* 调整边框颜色为纯黑色 */
  }
  
  .gantt-time-scale {
    display: flex;
    flex-direction: column; /* 初始为列布局，内部再调整 */
    flex-grow: 1;
  }
  
  .year-header-row {
    display: flex;
    border-bottom: 1px solid #000000; /* 调整边框颜色为纯黑色 */
    background-color: #f5f5f5;
    height: 30px;
  }
  
  .year-header {
    text-align: center;
    padding: 8px 0;
    font-weight: bold;
    border-right: 1px solid #000000; /* 调整边框颜色为纯黑色 */
    box-sizing: border-box;
  }
  
  .month-header-row {
    display: flex;
    border-bottom: 1px solid #000000; /* 调整边框颜色为纯黑色 */
    background-color: #f5f5f5;
    height: 30px;
  }
  
  .month-header {
    text-align: center;
    padding: 8px 0;
    font-weight: bold;
    border-right: 1px solid #000000; /* 调整边框颜色为纯黑色 */
    box-sizing: border-box;
  }
  
  .date-scale {
    display: flex;
    height: 50px; /* 增加高度以容纳两行内容 */
  }
  
  .date-cell {
    min-width: 25px; /* 每天的宽度 */
    text-align: center;
    border-right: 1px solid #000000; /* 调整边框颜色为纯黑色 */
    border-bottom: 1px solid #000000; /* 为每个单元格添加底部边框 */
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
  }
  
  .day-cell, .weekday-cell {
    width: 100%;
    text-align: center;
    padding: 2px 0;
    box-sizing: border-box;
  }
  
  .day-cell {
    font-weight: bold;
    font-size: 14px;
  }
  
  .weekday-cell {
    font-size: 12px;
    color: #666;
  }
  
  .gantt-body {
    display: flex;
  }
  
  .gantt-rows {
    min-width: 300px; /* 与header的宽度保持一致，增加宽度 */
    border-right: 1px solid #000000; /* 调整边框颜色为纯黑色 */
  }
  
  .gantt-row {
    display: flex;
    border-bottom: 1px solid #000000; /* 调整边框颜色为纯黑色 */
    min-height: 60px; /* 增加每行的高度，以容纳左侧三行文字 */
  }
  
  .gantt-row-info {
    min-width: 300px; /* 调整以适应左侧信息，增加宽度 */
    padding: 8px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  
  .row-label {
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 4px;
  }
  
  .row-order, .row-plan {
    font-size: 12px;
    color: #555;
    line-height: 1.4;
  }
  
  .gantt-bars {
    flex-grow: 1;
    position: relative;
    border-left: 1px solid #000000; /* 调整边框颜色为纯黑色 */
    min-height: 60px;
  }
  
  .gantt-grid-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    /* 只保留垂直网格线 */
    background-image: linear-gradient(to right, #000000 1px, transparent 1px);
    background-size: 25px 100%; /* 匹配dayWidth */
    z-index: 2; /* 使网格在甘特条上方 */
  }
  
  .gantt-bar {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background-color: #42b983;
    height: 20px;
    border-radius: 3px;
    z-index: 1; /* 确保甘特条在网格下方 */
  }
  
  .completion-tooltip {
    position: absolute;
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 5px 8px;
    border-radius: 4px;
    white-space: nowrap;
    z-index: 3; /* 确保提示框在最上层 */
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s, visibility 0.3s;
    top: -25px;
    left: 0;
  }
  
  .gantt-bar:hover .completion-tooltip {
    opacity: 1;
    visibility: visible;
  }
  </style>